<template>
	<div class="pagination">
		<!-- 上 -->
		<button :disabled="pageNo == 1" @click="$emit('pageNoInfo', pageNo - 1)">
			上一页
		</button>
		<button
			v-show="!(startANDend.startNum == 1)"
			@click="$emit('pageNoInfo', 1)"
			:class="{ curPage: pageNo == 1 }"
		>
			1
		</button>
		<button v-show="startANDend.startNum > 2">···</button>

		<!-- 中 -->
		<button
			v-for="continueI in continueArr"
			:key="continueI"
			@click="$emit('pageNoInfo', continueI)"
			:class="{ curPage: continueI == pageNo }"
		>
			{{ continueI }}
		</button>

		<!-- 下 -->
		<button v-show="startANDend.endNum < totalPage - 1">···</button>
		<button
			v-show="!(startANDend.endNum == totalPage)"
			@click="$emit('pageNoInfo', totalPage)"
			:class="{ curPage: pageNo == totalPage }"
		>
			{{ totalPage }}
		</button>
		<button
			:disabled="pageNo === totalPage"
			@click="$emit('pageNoInfo', pageNo + 1)"
		>
			下一页
		</button>

		<!-- ------- -->
		<button style="margin-left: 30px">共 {{ total }} 条</button>
	</div>
</template>

<script>
export default {
	name: "Pagination",
	props: ["pageNo", "pageSize", "total", "continues"],

	data() {
		return {
			continueArr: [],
		};
	},
	computed: {
		// 总页码数
		totalPage() {
			// 向上取整
			return Math.ceil(this.total / this.pageSize);
		},

		/* 计算continues的范围 */
		startANDend() {
			let pageNo = Number(this.pageNo);
			let totalPage = Number(this.totalPage);
			let continues = Number(this.continues);

			let startNum = 0,
				endNum = 0;
			// 特殊情况1：总数据量太少，不需要continues出场
			if (totalPage < continues) {
				startNum = 1;
				endNum = totalPage;
			} else {
				// 正常情况,框出comtinues的范围
				startNum = pageNo - parseInt(continues / 2);
				endNum = pageNo + parseInt(continues / 2);

				// 特殊情况2：小于了continue的最小边界
				if (startNum < 1) {
					startNum = 1;
					endNum = continues;
				}
				// 特殊情况3：超出了continue的最大边界
				if (endNum > totalPage) {
					startNum = totalPage - continues + 1;
					endNum = totalPage;
				}
			}
			return { startNum, endNum };
		},
	},
	watch: {
		startANDend: {
			immediate: true,
			handler() {
				// console.log(this.startANDend.endNum);
				// 生成指定end 长度的数组
				const arr = Array(this.startANDend.endNum + 1).keys();
				// 从start开始 向后截取
				this.continueArr = Array.from(arr).splice(this.startANDend.startNum);
				// console.log(1111);
			},
		},
	},
	created() {},
};
</script>

<style lang="less" scoped>
.pagination {
	text-align: center;
	button {
		margin: 0 5px;
		background-color: #f4f4f5;
		color: #606266;
		outline: none;
		border-radius: 2px;
		padding: 0 4px;
		vertical-align: top;
		display: inline-block;
		font-size: 13px;
		min-width: 35.5px;
		height: 28px;
		line-height: 28px;
		cursor: pointer;
		box-sizing: border-box;
		text-align: center;
		border: 0;

		&[disabled] {
			color: #c0c4cc;
			cursor: not-allowed;
		}

		&.active {
			cursor: not-allowed;
			background-color: #409eff;
			color: #fff;
		}
	}

	.curPage {
		background: #b2e0df;
	}
}
</style>
